package com.zx._03_并发.chapter_06_compent;

import com.zx.common.util.ThreadUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;

/**
 * 同步组件——Future
 */
@Slf4j
public class Demo_09_Future {

    public static void main(final String[] args) throws Exception {
        final ExecutorService pool = Executors.newCachedThreadPool();
        final Future<String> task = pool.submit(() -> {
            ThreadUtil.sleepMill(1500);
            return "111";
        });
        System.out.println(task.get(1, TimeUnit.SECONDS));

        final Future<String> task2 = pool.submit(() -> {
            ThreadUtil.sleepMill(1500);
            return "111";
        });
        System.out.println(task2.get(1, TimeUnit.SECONDS));

        pool.shutdown();
    }

    public static void main2(final String[] args) throws InterruptedException, ExecutionException {
        final ExecutorService pool = Executors.newCachedThreadPool();
        final List<Future<String>> li = new ArrayList<Future<String>>();
        for (int i = 0; i < 1000; i++) {
            final boolean flag = i % 5 == 0;
            final Future<String> submit = pool.submit(() -> {
                Thread.sleep(1000L);
                if (flag) {
                    return "exception";
                }
                return "ok";
            });
            li.add(submit);
        }

        for (final Future<String> future : li) {
            log.info(future.get());
        }
        pool.shutdown();
    }

    public static void main1(final String[] args) throws InterruptedException, ExecutionException {
        final ExecutorService pool = Executors.newCachedThreadPool();
        final List<Future<String>> li = new ArrayList<Future<String>>();
        for (int i = 0; i < 1000; i++) {
            final boolean flag = i % 5 == 0;
            final FutureTask<String> task = new FutureTask<>(() -> {
                Thread.sleep(1000L);
                if (flag) {
                    return "exception";
                }
                return "ok";
            });
            pool.submit(task);
            li.add(task);
        }
        for (final Future<?> future : li) {
            log.info(future.get().toString());
        }
        pool.shutdown();
    }
}
